import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useAuthStore} from '@/stores/auth.js'
import {TOKEN_KEY} from "@/api/_const.js";
import router, {login} from "@/router/index.js";

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在请求头中添加token
        const token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        // 根据业务状态码处理
        const contentType = response.headers['content-type']
        if (contentType && contentType.toLocaleLowerCase() === "application/json") {
            const res = response.data
            if (res.code !== 200) {
                // 401: 未认证
                if (res.code === 401) {
                    const authStore = useAuthStore()
                    authStore.reset()
                    router.push({name: login})
                }
                ElMessage({message: res.message || '接口异常', type: 'error', duration: 5 * 1000})
                console.error('--test', response)
                return Promise.reject(res)
            }
            return res
        }
        return response
    },
    (error) => {
        console.log('err' + error)
        return Promise.reject(error)
    }
)

export default service